#include"Mutex.hpp"

int ticket=1000;

pthread_mutex_t glock=PTHREAD_MUTEX_INITIALIZER;
std::mutex cpplock;

class ThreadData
{
public:
    ThreadData(MutexModule::Mutex& mutex,const std::string&name)
    :_mutex(mutex)
    ,_name(name)
    {}
    MutexModule::Mutex& _mutex;
    std::string _name;
};

void*Routine(void*args)
{   
    ThreadData* td=static_cast<ThreadData*>(args);
    while(true)
    {
        //临界区 加锁
        //pthread_mutex_lock(&glock);
        //cpplock.lock();

        //锁的获取和释放与变量生命周期绑定
        MutexModule::MutexGuard mg(td->_mutex);
        if(ticket>0)
        {
            usleep(1000);
            printf("%s sells ticket:%d\n", td->_name.c_str(), ticket);
            ticket--;
            //pthread_mutex_unlock(&glock);
            //cpplock.unlock();
        }
        else
        {
            //pthread_mutex_unlock(&glock);
            //cpplock.unlock();
            break;
        }
        usleep(123);
    }
    return nullptr;
}

int main()
{
    //局部锁  需要作为参数传递给线程的函数
    // pthread_mutex_t lock;
    // pthread_mutex_init(&lock,nullptr);

    //锁的创建与销毁与变量生命周期绑定
    MutexModule::Mutex mutex;

    pthread_t pd1;
    ThreadData*td1=new ThreadData(mutex,"thread-1");
    pthread_create(&pd1,nullptr,Routine,(void*)td1);

    pthread_t pd2;
    ThreadData*td2=new ThreadData(mutex,"thread-2");
    pthread_create(&pd2,nullptr,Routine,(void*)td2);

    pthread_t pd3;
    ThreadData*td3=new ThreadData(mutex,"thread-3");
    pthread_create(&pd3,nullptr,Routine,(void*)td3);

    pthread_t pd4;
    ThreadData*td4=new ThreadData(mutex,"thread-4");
    pthread_create(&pd4,nullptr,Routine,(void*)td4);

    pthread_join(pd1,nullptr);
    pthread_join(pd2,nullptr);
    pthread_join(pd3,nullptr);
    pthread_join(pd4,nullptr);

    //pthread_mutex_destroy(&lock);
    return 0;
}